package com.liushuo.service;

import com.liushuo.VO.AddExerciseSetVO;
import com.liushuo.dao.ExerciseSetDao;
import com.liushuo.dao.QuestionDao;
import com.liushuo.entity.ExerciseSet;
import com.liushuo.entity.Question;
import com.liushuo.util.DBUtil;
import com.liushuo.util.ThreadLocalUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

public class ExerciseSetService {

    private final QuestionService questionService = new QuestionService();
    private final ExerciseSetDao exerciseSetDao = new ExerciseSetDao();
    private final QuestionDao questionDao = new QuestionDao();


    public AddExerciseSetVO addExerciseSet(int totalQuestions, int questionsWithParentheses, int gradeLevel) {
        Connection conn = null;
        boolean commit = false;
        try {
            conn = DBUtil.getConnection();
            if (conn != null) {
                conn.setAutoCommit(false);
            }

            List<Question> questions = questionService.generateQuestions(totalQuestions, questionsWithParentheses, gradeLevel);
            questionDao.save(questions, conn);
            String userId = ThreadLocalUtil.getUserId();
            ExerciseSet exerciseSet = ExerciseSet.builder()
                    .createUserId(userId)
                    .startQuestionId((long) questions.getFirst().getId())
                    .endQuestionId((long) questions.getLast().getId())
                    .gradeLevel(String.valueOf(gradeLevel))
                    .score("0")
                    .createTime(new Timestamp(System.currentTimeMillis()))
                    .build();
            exerciseSetDao.save(exerciseSet, conn);

            conn.commit();
            commit = true;
            return AddExerciseSetVO.builder()
                    .exerciseSet(exerciseSet)
                    .questions(questions)
                    .build();
        } catch (Exception e) {
            if (conn != null) {
                try {
                    System.out.println("发生异常时回滚事务" + e.getMessage());
                    conn.rollback();
                } catch (Exception e2) {
                    System.out.println("回滚失败" + e2.getMessage());
                }
            }
            throw new RuntimeException(e);
        } finally {
            if (conn != null) {
                try {
                    if (!commit) {
                        conn.setAutoCommit(true);
                    }
                    conn.close();
                } catch (SQLException closeEx) {
                    closeEx.printStackTrace();
                }
            }
        }
    }

    public void setExerciseSetScore(Long exerciseSetId, int score) {
        exerciseSetDao.setExerciseSetScore(exerciseSetId, score);
    }

    public List<ExerciseSet> getExerciseSetByUserIdAndDate(String userId,Date startDate, Date endDate) {
        return exerciseSetDao.getExerciseSetByUserIdAndDate(userId, startDate, endDate);
    }

    public AddExerciseSetVO importQuestions(List<Question> questions) {
        Connection conn = null;
        boolean commit = false;
        try {
            conn = DBUtil.getConnection();
            if (conn != null) {
                conn.setAutoCommit(false);
            }
            questionDao.save(questions, conn);
            String userId = ThreadLocalUtil.getUserId();
            ExerciseSet exerciseSet = ExerciseSet.builder()
                    .createUserId(userId)
                    .startQuestionId((long) questions.getFirst().getId())
                    .endQuestionId((long) questions.getLast().getId())
                    .score("0")
                    .createTime(new Timestamp(System.currentTimeMillis()))
                    .build();
            exerciseSetDao.save(exerciseSet, conn);
            conn.commit();
            commit = true;
            return AddExerciseSetVO.builder()
                    .exerciseSet(exerciseSet)
                    .questions(questions)
                    .build();
        } catch (Exception e) {
            if (conn != null) {
                try {
                    System.out.println("发生异常时回滚事务" + e.getMessage());
                    conn.rollback();
                } catch (Exception e2) {
                    System.out.println("回滚失败" + e2.getMessage());
                }
            }
            throw new RuntimeException(e);
        } finally {
            if (conn != null) {
                try {
                    if (!commit) {
                        conn.setAutoCommit(true);
                    }
                    conn.close();
                } catch (SQLException closeEx) {
                    closeEx.printStackTrace();
                }
            }
        }
    }


}
